In this tutorial we will learn how to access and manipulate the image's meta-data form the header.
During the image loading tutorial we obtained beside the image data as numpy array an additional header object. Let's first load our usual image.
In [1]:
%matplotlib inline
from medpy.io import load
import matplotlib.pyplot as plt
import matplotlib.cm as cm
i, h = load("flair.nii.gz")
plt.imshow(i, cmap = cm.Greys_r);
Now let's take a look at the header.
In [3]:
print(h)
That is quite a lot of information and the header appear to be of class 'nibabel.nifti1.Nifti1Image'. The reason behind this is that MedPy relies on third party librarier to save and load image. To keep the compatibility high and the maintenance requirements at a minimum, MedPy does not posess a dedicated header object, but instead returns the third party libraries image object as pseudo-header (don't worry, the image data is not kept twice).
Depending on the third party library used, a different kind of header object can be returned. To provide image format independent access to the most important header attributes, MedPy provides some accessor-functions that work with all type of headers.
To query the image's voxel spacing, you can use the following.
In [8]:
from medpy.io import header
print header.get_pixel_spacing(h)
And correspondingly for the offest.
In [9]:
print header.get_offset(h)
Both of these values can also be set,
In [10]:
header.set_pixel_spacing(h, (0.8, 1.2))
print header.get_pixel_spacing(h)
Saving the array with the modified header, the new meta-data are stored alongside the image.
In [11]:
from medpy.io import save
save(i, "flair_distorted.nii.gz", h, force=True)
j, hj = load("flair_distorted.nii.gz")
print header.get_pixel_spacing(h)
Further meta-data from the headers is largely incompatible between formats. If you require access to additional header attributes, you can do this by querying the image header object directly. In the above case of a NiBabel class, you can, for example, query the infamous 'qform_code' of the NIfTI format.
In [12]:
print(h.header['qform_code'])
But be warned that such an approach leads to image format and image loade dependent code.